<template>
  <el-card>
    <div slot="header">
      <h3>批量新增-管理信息</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <el-button
          v-if="showBtn('关联商品')"
          type="text"
          size="large"
          @click="handleAssociatedGoods"
          >关联商品</el-button
        >
        <el-button
          v-if="tableInfo.dataSource.length > 0"
          type="text"
          size="large"
          @click="handleExportData"
          :loading="loading.export"
          >模板导出</el-button
        >
        <a
          ><Upload
            :show-upload-list="false"
            :format="['xlsx', 'xls', 'csv']"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-format-error="handleUploadFormatError"
            :before-upload="handleBeforeUpload"
            :action="`${uploadBaseURL}sysback/batch/prepare/allmanaging/saveAllManagingToPage`"
            ><el-button type="text" size="large">模板导入</el-button></Upload
          ></a
        >
        <el-button
          v-if="tableInfo.dataSource.length > 0"
          type="text"
          size="large"
          @click="handleSubmitData"
          :loading="loading.submit"
          >提交</el-button
        >
      </el-row>
      <el-row>
        <general-render-table
          :loading="loading.table"
          :data-source="tableInfo.dataSource"
          :columns="tableInfo.columns"
          @handleCancelSelect="handleCancelSelect"
          @handleChangeCheckBox="handleChangeCheckBox"
          @handleChangeRadio="handleChangeRadio"
        />
      </el-row>
    </div>
    <!-- 关联弹框 -->
    <SpuAssociatedDialog
      ref="spuModal"
      :columns="associatedGoods.columns"
      :requestApi="associatedGoods.requestApi"
      :requestParams="associatedGoods.requestParams"
      :distinctParams="associatedGoods.distinctParams"
      @getRowList="getAssociatedGoodsAction"
    />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage'
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission'
/* components */
import GeneralRenderTable from '@/pages/commodity/modules/components/generalRenderTable';
import SpuAssociatedDialog from '@/components/common/dialog/associatedGoods/spuAssociatedDialog';
/* mixins */
import spuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/spuDimension';
/* constants */
import { requiredParams } from '@/components/common/dialog/associatedGoods/constants/spuDimension';
import { ADD_MANAGE_INFO_AMOUNT } from '@/constants/exportAmountLimit';
/* utils */
import { isResponseSuccess } from '@/utils/bizUtils';
import { getAttributeTypeFn } from '@/pages/commodity/modules/utils';
import { getDealManageDataToApiFn, setWarningDialogFunc } from '@/pages/commodity/modules/utils/manageInfoRequireUtils';
export default {
  mixins: [spuDimensionMixins],
  components: {
    GeneralRenderTable,
    SpuAssociatedDialog
  },
  data () {
    return {
      loading: {
        table: false, // 表格loading
        export: false, // 导出按钮loading
        submit: false // 提交按钮loading
      },
      tableInfo: {
        dataSource: [], // 表格数据源
        columns: [] // 表格columns
      },
      notShowAttrList: ['logistics_stock', 'manage_distributing_centre', 'manage_packlist'], // 无需渲染的表格列
      initManageTableColumns: [ // 表格初始columns
        {
          title: '品类',
          key: 'categoryPath',
          width: 120
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          width: 120
        },
        {
          title: '商品名称',
          key: 'productNameFinal',
          width: 120
        },
        {
          title: '品牌',
          key: 'brandName',
          width: 120
        }
      ],
      associatedGoods: {
        requestApi: {
          url: ['/sysback/batch/prepare/allmanaging/getProductList'], // 关联商品查询接口
          type: 'post'
        },
        requestParams: requiredParams.requestParams, // 关联商品查询接口所需入参
        distinctParams: requiredParams.distinctParams, // 关联商品查询接口区别未关联和已关联的入参
        columns: [ // 关联商品弹框表格columns
          { type: 'selection', width: 60, align: 'center' },
          { title: '商品名称', key: 'productNameFinal', width: 150 },
          { title: 'SPU编码', key: 'spuNo', width: 180 },
          { title: '商品分类', key: 'categoryPath', width: 180 },
          { title: '管理区域', key: 'manageAreaName', width: 180 },
          { title: '规格参数', key: 'saleAttrInfo', width: 150 },
          { title: '品牌', key: 'brandName', width: 150 },
          { title: '操作', slot: 'action', align: 'center', fixed: 'right', minWidth: 100 }
        ],
      },
      apiObj: {
        commitBasicInfo: {
          url: '/sysback/batch/prepare/allmanaging/commitAllManaging', // 提交接口地址
          type: 'post' // 接口请求类型
        },
        exportPageToExcelPost: {
          url: '/sysback/batch/prepare/allmanaging/exportPageToExcelPost', // 表单导出接口地址
          type: 'post' // 接口请求类型
        },
      }
    }
  },
  computed: {
    ...mapGetters('permissions/systemBtns', [
      'showBtn'
    ]),
  },
  mounted () {
    this.tableInfo.columns = _.cloneDeep(this.initManageTableColumns);
  },
  methods: {
    /* 初始化表格数据 */
    initTableDataFunc (source) {
      this.tableInfo.columns = _.cloneDeep(this.initManageTableColumns);
      this.tableInfo.dataSource = [];
      this.dealTableColumnsThFunc(source);
      this.tableInfo.columns.push({
        title: '操作',
        key: 'action',
        width: 150,
        fixed: 'right'
      });
    },
    /* 处理表头方法 */
    dealTableColumnsThFunc (source) {
      let dataList = source.reduce((value, item, index) => {
        let { productUuid, productNameFinal, brandName, categoryPath, spuNo, saleAttrInfo, manageArea } = item.main
        value.push({ productUuid, productNameFinal, brandName, categoryPath, spuNo, saleAttrInfo, manageArea })
        let nameList = Object.keys(item)
        let notForEachName = ['authDepartments', 'thirdPlatList', 'cityList']
        nameList.forEach(nameType => {
          if (!_.isArray(item[nameType]) || notForEachName.includes(nameType)) { return }
          value[index][nameType] = []
          item[nameType].forEach(thItem => {
            if (thItem.attrType === '04') {
              thItem.valueName = thItem.valueName ? _.clone(thItem.valueName).split(/,|，|\s+/) : [] // 以中英文逗号、空格（一个或多个）分割字符串
            }
            value[index][thItem.attrUuid] = thItem
            value[index][nameType].push(thItem.attrUuid)
            if (index === 0 && !this.notShowAttrList.includes(thItem.attrUuid)) {
              this.tableInfo.columns.push({
                title: thItem.attrName,
                align: 'center',
                key: thItem.attrUuid,
                type: getAttributeTypeFn(thItem.attrType),
                required: thItem.attrMust === '1' || false,
                disabled: thItem.canEdit === 'N' || false,
                width: thItem.attrType === '04' ? '180' : '140'
              })
            }
          })
        })
        return value
      }, [])
      this.tableInfo.dataSource = _.cloneDeep(dataList)
    },
    /* 据归类UUID，查询税类代码taxCateNo、销售税率taxRate */
    getTaxInfoDataAction (data) {
      let { allValueOptions, val } = data
      let target = _.find(allValueOptions, item => { return item.optionHtml === val })
      let uuid = target.optionValue
      let params = { uuid }
      return new Promise((resolve, reject) => {
        this.loading.table = true
        ApiRequest(`/sysback/addsingleproduct/basicinfo/getClassificationByUuid?uuid=${uuid}`, 'post', params).then(res => {
          this.loading.table = false
          if (!isResponseSuccess(res)) {
            resolve(false);
            return false;
          }
          let data = {
            taxCateNo: res.retData.taxCateNo,
            taxRate: res.retData.taxRate
          }
          resolve(data)
        }).catch(() => {
          this.loading.table = false
        })
      })
    },
    /* 处理单选下拉逻辑 */
    handleChangeRadio (data) {
      let { row, val, columnName } = data
      if (columnName === 'tax_classify') { // 如果当前切换的是归类名称字段，就调用归类信息接口
        this.getTaxInfoDataAction({ val, allValueOptions: row.tax_classify.allValueOptions }).then(retData => {
          if (!retData) { return false }
          row.tax_code.valueName = retData.taxCateNo;
          row.tax_rate.valueName = retData.taxRate;
        })
      }
      /* 选择是否季节性商品 */
      if (columnName === 'manage_season_product' && val === '否') {
        row.manage_stock_period.valueName = ''; // 囤货期
        row.manage_soldout_period.valueName = ''; // 下架期
      }
    },
    /* 处理多选下拉逻辑 */
    handleChangeCheckBox (data) {
      let { row, val, columnName } = data;
      const notSaleFlag = val.includes('不销售');
      const notSaleIndex = val.indexOf('不销售');
      if (notSaleFlag) {
        if (val.length === notSaleIndex + 1) {
          row[columnName].valueName = ['不销售'];
        } else {
          row[columnName].valueName.splice(notSaleIndex, 1);
        }
      } else {
        row[columnName].valueName = val;
      }
    },
    /* 取消对应表格row */
    handleCancelSelect (data) {
      let { row } = data;
      this.handleDeleteSpuRow(row, this.tableInfo.dataSource, 'productUuid');
      this.getAssociatedGoodsAction();
    },
    /* 关联商品 */
    handleAssociatedGoods () {
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.CHANGE_MODAL_SWITCH(true);
      /* 打开弹框直接查询数据
      this.$nextTick(() => {
        this.$refs.spuModal.getDataListAction()
      })
      */
    },
    /* 关联商品获取表格数据 */
    getAssociatedGoodsAction () {
      let dataList = this.getListFromMapFn().map(value => {
        return value.uuid;
      });
      let data = dataList;
      if (dataList.length !== 0) {
        this.loading.table = true;
        ApiRequest(`/sysback/batch/prepare/allmanaging/queryAllManagingList`, 'post', data, false).then(res => {
          this.loading.table = false;
          if (!isResponseSuccess(res)) {
            return false;
          }
          this.initTableDataFunc(res.retData);
        }).catch(() => {
          this.loading.table = false;
        })
      } else {
        this.tableInfo.dataSource = [];
      }
    },
    /* 重置售卖平台的方法
       保存校验时，当商品四级类的是否限制类为危化品，并且是一级的时候（后端校验），将售卖平台的普通平台的勾选取消)
    */
    resetSalePlatFunc (spuNoList) {
      if (!spuNoList) { return false }
      spuNoList.forEach(spuNo => {
        let index = this.tableInfo.dataSource.findIndex(item => {
          return item.spuNo === spuNo;
        })
        if (index === -1) { return false }
        let normalIndex = this.tableInfo.dataSource[index].marketing_saleplat.valueName.indexOf('普通平台');
        if (normalIndex === -1) { return false }
        this.tableInfo.dataSource[index].marketing_saleplat.valueName.splice(normalIndex, 1);
      })
    },
    /* 提交数据 */
    handleSubmitData () {
      if (this.tableInfo.dataSource.length > ADD_MANAGE_INFO_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${ADD_MANAGE_INFO_AMOUNT}`);
      }
      let { submitResults, errorMessage } = getDealManageDataToApiFn({ tableData: this.tableInfo.dataSource, type: 'add', notShowAttrList: this.notShowAttrList })
      if (errorMessage) { return this.$Message.warning(errorMessage) }
      let { url, type } = this.apiObj.commitBasicInfo;
      this.loading.submit = true;
      ApiRequest(url, type, submitResults, false).then(res => {
        this.loading.submit = false;
        if (!isResponseSuccess(res)) {
          setWarningDialogFunc(this, res, this.resetSalePlatFunc);
          return false;
        }
        this.$message.success('提交成功');
        this.tableInfo.dataSource = [];
        this.$router.push({ name: 'commodityNotPerfection' }) // 跳转待准入页面
      }).catch(() => {
        this.loading.submit = false;
      })
    },
    /* 导出数据 */
    handleExportData () {
      let { submitResults } = getDealManageDataToApiFn({ tableData: this.tableInfo.dataSource, type: 'add', notShowAttrList: this.notShowAttrList })
      let { url, type } = this.apiObj.exportPageToExcelPost;
      this.loading.export = true;
      ApiRequestExportTable(url, type, submitResults, false).then(res => {
        this.loading.export = false;
        const blob = new Blob([res], {
          type: 'application/octet-stream',
        });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '批量维护管理信息.xlsx';
        link.click();
        window.URL.revokeObjectURL(blob); // 释放掉blob对象
      }).catch(() => {
        this.loading.export = false;
        this.$message.error('导出失败');
      });
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.loading.table = false;
      this.$message.error('格式错误');
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.loading.table = true;
      this.tableInfo.dataSource = [];
    },
    /* 上传成功 */
    handleUploadSuccess (res) {
      this.loading.table = false;
      if (!isResponseSuccess(res)) {
        // 如果接口返回失败,就打印失败信息
        return this.$message.error(res.retMessage);
      }
      // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
      this.initTableDataFunc(res.retData);
    },
    /* 上传失败 */
    handleUploadError () {
      this.loading.table = false;
      this.$message.error('上传失败');
    },
  }
}
</script>
<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
